package com.example.lcpharmacy.lcutils.filter;


import com.example.lcpharmacy.lcutils.Pagination;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionFilter implements Filter {

    static String[] NO_FILTER = {
            "/client/user/js/", "/client/user/css/",
            "/client/user/dist/", "/client/user/iconfont",
            "/client/user/slick/", "/client/user/img/","/login",
            "/client/home/index.html",
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();

        //不需要走过滤器的uri
        if (!isNeedFilter(uri)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
            //需要走过滤器
        } else {
            System.out.println("filter：" + uri);
            //1、查看会话 是否已经登录
//            if(session.getAttribute("currentUser")) {
//                filterChain.doFilter(servletRequest,servletResponse);
//            }else{
            //2.没有登录，重定向到登录页面先进行登录
            response.sendRedirect(request.getContextPath() + "/client/user/login.html");
//            }
        }
    }

    private static Boolean isNeedFilter(String uri){
        for (String  item: NO_FILTER) {
            if(uri.contains(item)){
                return false;
            }
        }
        return true;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
